import store from '../store';
let audioQueue = []; // 创建一个音频播放队列  
let orderQueue = []; // 创建一个消息队列  
let currentAudio = null; // 当前播放的音频  
let currentOrder = null; // 当前订单消息 
class websocketUtil {
	constructor(url, time) {
		this.is_open_socket = false //避免重复连接
		this.url = url //地址
		this.data = null
		//心跳检测
		this.timeout = time //多少秒执行检测
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectTimeOut = null //重连之后多久再次重连

		if (store.state.shoptoken) {
			try {
				return this.connectSocketInit()
			} catch (e) {
				this.is_open_socket = false
				this.reconnect();
			}
		}
	}
	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常！");
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(this.heartbeatInterval)
			this.is_open_socket = true;
			this.data = {
				'token': uni.getStorageSync('shoptoken'),
			}
			this.send(JSON.stringify(this.data));
			this.start();
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.socketTask.onMessage((res) => {
				console.log(res.data, '订单来了')
				let data = JSON.parse(res.data);
				let audio = '';
				if (data.event == 'NEW_ORDER') {
					let orderdata = data.body
					if (store.state.lang == 'ug') {
						audio =
							`https://utts.edu.izdax.cn/api/tts?text=يىڭى زاكاز كەلدى ،${orderdata.table_number}-ئۈستەل`; // 设置音频文件路径
					} else {
						audio =
							`https://ss0.baidu.com/6KAZsjip0QIZ8tyhnq/text2audio?tex=你有新的订单,${orderdata.table_number}号桌&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=10&spd=5`; // 设置音频文件路径  	
					}
					this.enqueueAudio(audio, 'order', data.body);
				}
				if (data.event == 'PAID') {
					//
					let paydata = data.body
					console.log(paydata, '+++++++++')
					if (paydata.status == 0) {
						if (store.state.lang == 'ug') {
							audio =
								`https://utts.edu.izdax.cn/api/tts?text=${paydata.table_number}-ئۈستەل تاماق بۇيرۇتتى ،${paydata.fee} يۈەن`; // 设置音频文件路径
						} else {
							audio =
								`https://ss0.baidu.com/6KAZsjip0QIZ8tyhnq/text2audio?tex=微信支付${paydata.fee}元&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=10&spd=5`; // 设置音频文件路径  	
						}
					} else {
						if (store.state.lang == 'ug') {
							audio =
								`https://utts.edu.izdax.cn/api/tts?text=پۇل تۆلەش مۇۋاپىقيەتلىك بولدى ،${paydata.fee} يۈەن`; // 设置音频文件路径
						} else {
							audio =
								`https://ss0.baidu.com/6KAZsjip0QIZ8tyhnq/text2audio?tex=微信支付${paydata.fee}元&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=10&spd=5`; // 设置音频文件路径  	
						}
					}

					this.enqueueAudio(audio, 'paid', data.body);
				}
			});
		})
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			console.log("已经被关闭了")
			this.is_open_socket = false;
			this.reconnect();
		})
	}

	/**  播放声音开始  **/

	playAudio(src) {
		let audio = uni.createInnerAudioContext(); // 创建音频上下文对象
		currentAudio = audio;
		audio.src = src;
		audio.onPlay(() => {
			console.log('音频开始播放');
		});
		//报错
		audio.onError((res) => {
			this.playNextAudio();
			console.error('音频播放错误', res);
		});
		//结束
		audio.onEnded(() => {
			console.log('音频播放结束');
			// 当前音频播放结束，尝试播放下一个音频  
			this.playNextAudio();
		});
		audio.play();
	}

	// 播放下一个音频  
	playNextAudio() {
		if (currentAudio) {
			currentAudio.onEnded(null); // 清除上一个音频的结束事件监听  
		}
		if (audioQueue.length > 0) {
			currentAudio = audioQueue.shift(); // 从队列中取出下一个音频  
			currentOrder = orderQueue.shift();
			if (currentOrder.type == 'order') {
				store.commit('Setneworder', currentOrder.order);
			} else {
				store.commit('Setpaid', currentOrder.order);
			}
			this.playAudio(currentAudio); // 播放当前音频  
		} else {
			currentAudio = null; // 队列为空，设置当前音频为null  
		}
	}

	// 添加音频到队列  
	enqueueAudio(src, type, data) {
		orderQueue.push({
			order: data,
			type: type
		});
		audioQueue.push(src);
		if (!currentAudio) {
			// 如果当前没有播放的音频，则开始播放队列中的第一个音频  
			this.playNextAudio();
		}
	}


	//发送消息
	send(value) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		this.socketTask.send({
			data: value,
			async success() {
				console.log("消息发送成功");
			},
		});
	}
	//开启心跳检测
	start() {
		this.heartbeatInterval = setInterval(() => {
			this.data = {
				'token': uni.getStorageSync('shoptoken'),
			}
			this.send(JSON.stringify(this.data));
		}, this.timeout)
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				this.connectSocketInit();
			}, 3000)
		}
	}
	//外部获取消息
	getMessage(callback) {
		this.socketTask.onMessage((res) => {
			return callback(res)
		})
	}

}

module.exports = websocketUtil